<!--
 * @description  : 实地核查方位图-地图坐标页面
 * @create       : 2024-7-30
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"> </theme-navbar>
    <!-- #endif -->
    <view class="m-content">
      <view class="tips">确认商户位置信息，如需修改请<view class="bold">拖动图标</view>重新确定</view>
      <view :style="{ width: getContainerWidth(), height: getContainerHeight() }" id="container"></view>
      <view class="m-market">
        <u-row :gutter="8" class="row">
          <u-col :span="3">位置：</u-col>
          <u-col :span="9" class="row-value">{{ getRegeocodeInfo() }}</u-col>
          <br />
          <u-col :span="3">经度/纬度：</u-col>
          <u-col :span="9" class="row-value">{{ newPosition.lng }}/{{ newPosition.lat }}</u-col>
        </u-row>
        <u-row :gutter="10" class="row" @click="handleChooseGrid">
          <u-col :span="3">网格名称：</u-col>
          <u-col :span="9" class="row-value">{{ curGridInfo.gridName }}</u-col>
          <br />
          <u-col :span="3">承载量：</u-col>
          <u-col :span="2" class="row-value hightlight">{{ curGridInfo.licPlanQty }}</u-col>
          <u-col :span="3.5">当前商户数：</u-col>
          <u-col :span="2.5" class="row-value">{{ curGridInfo.licCurrQty }}</u-col>
          <u-icon name="arrow-right" class="arrow"></u-icon>
        </u-row>
        <u-row class="row">
          <u-col :span="12" class="row-button">
            <u-button type="primary" @click="handleNextStep">
              确定位置信息，下一步
            </u-button>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script>
import { AMapMixin } from "@/common/AMapMixin.js";
import { SET_MAP_LAT_LON } from "@/config/setting.config.js";
// 截图工具类  fsx 2024-2-23 开始
import { screenshots } from "@/common/ScreenshotsUtil.js";
// 截图工具类  fsx 2024-2-23 结束
import fabButton from "@/components/uni-fab.vue";
import commonService from "@/service/common/common.service.js";
import certificateService from "@/service/certificate/certificate.service.js";

export default {
  onLoad(opt) {
    this.oldPosition = opt;
    this.newPosition.lng = this.oldPosition.lng || "";
    this.newPosition.lat = this.oldPosition.lat || "";
    opt.gridUuid && this.initGridInfo(opt.gridUuid);
  },
  onShow() {
    uni.$on("setGridInfo", data => {
      uni.$off("setGridInfo");
      this.curGridInfo = JSON.parse(data.info);
    });
  },
  onUnload() {
    uni.$off("setGridInfo");
  },
  mixins: [AMapMixin],
  data() {
    return {
      oldPosition: {},
      newPosition: {
        lng: "",
        lat: ""
      },
      currPosition: undefined,
      positionPicker: undefined,
      curGridInfo: {}
    };
  },
  computed: {},
  methods: {
    // 初始化网格信息
    initGridInfo(id) {
      this.$u.loading("加载中...");
      certificateService.getGridInfoById({ gridUuid: id }).then(res => {
        this.$u.hideLoading();
        if (res.success) {
          const { gridUuid, gridName, licPlanQty, licCurrQty } = res.bean;
          this.curGridInfo = { gridUuid, gridName, licPlanQty, licCurrQty };
        }
      });
    },
    initAmap() {
      let self = this;
      // #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
      this.$deviceApi.geolocation().then(
        res => {
          self.curPos = [res.longitude, res.latitude];
          self.setMapInstance([res.longitude, res.latitude]);
        },
        err => {
          self.justInitMap();
        }
      );
      // #endif
      // #ifdef H5-ONLY
      self.curPos = SET_MAP_LAT_LON;
      self.setMapInstance(SET_MAP_LAT_LON);
      // #endif
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight + "px";
      // #ifdef H5-DINGDING || H5-WECHAT
      p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + "px";
      // #endif
      return p;
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + "px";
    },
    getRegeocodeInfo() {
      let tmp = "";
      if (!this.currPosition || !this.currPosition.regeocode) {
        return tmp;
      }
      try {
        const name = this.currPosition.regeocode.aois.length
          ? this.currPosition.regeocode.aois[0].name
          : this.currPosition.regeocode.crosses.length
          ? this.currPosition.regeocode.addressComponent.township + this.currPosition.regeocode.crosses[0].second_name
          : this.currPosition.regeocode.addressComponent.township;
        tmp = this.currPosition.regeocode.addressComponent.province + this.currPosition.regeocode.addressComponent.district;
        tmp += name;
		console.log(this.$storage.get("curConfirmInfo"))
        this.$storage.set("curConfirmInfo", {
          ...this.$storage.get("curConfirmInfo"),
          ...{curPositionName: name}
        });
      } catch (e) {
        console.log(e);
      }
      return tmp;
    },
    setMapInstance(cords) {
      let self = this;
      if (!self.hasInited) return;
      self.curCords = new AMap.LngLat(cords[0], cords[1]);
      self.amap = new AMap.Map("container", {
        center: self.curCords,
        showControlButton: true,
        zoom: 18
      });
      self.setCurrentPointMarker();
      self.$modal.hideLoading();
      self.loadPlugin("AMap.ControlBar", function() {
        const controlBar = new AMap.ControlBar({
          position: {
            top: "40px",
            right: "10px"
          }
        });
        self.amap.addControl(controlBar);
      });
      AMapUI.loadUI(["misc/PositionPicker"], function(PositionPicker) {
        AMap.PositionPicker = PositionPicker;
        self.loadMarkList();
      });
    },
    setNewPosition(pos) {
      this.newPosition.lng = pos.lng + "";
      this.newPosition.lat = pos.lat + "";
    },
    loadMarkList() {
      let self = this;
      self.positionPicker = new AMap.PositionPicker({
        mode: "dragMarker",
        map: self.amap,
        iconStyle: {
          url: require("@/static/market/new-location.png"),
          ancher: [7, 50],
          size: [20, 30]
        }
      });
      self.amap.on("click", function(positionResult) {
        self.positionPicker.start(new AMap.LngLat(positionResult.lnglat.getLng(), positionResult.lnglat.getLat()));
        console.log("getLng", positionResult.lnglat.getLng());
        console.log("getLat", positionResult.lnglat.getLat());
      });
      // 修改选址
      self.positionPicker.on("success", function(positionResult) {
        self.currPosition = {
          accuracy: 0,
          altitude: 0,
          altitudeAccuracy: null,
          heading: null,
          latitude: positionResult.position.getLat(),
          longitude: positionResult.position.getLng(),
          speed: null,
          detailAddress: positionResult["address"],
          regeocode: positionResult.regeocode
        };
        self.setNewPosition({
          lng: positionResult.position.getLng(),
          lat: positionResult.position.getLat()
        });
      });
      self.positionPicker.on("fail", function(positionResult) {
        console.log("获取点坐标失败");
      });
      if (self.oldPosition.lng && self.oldPosition.lat && Number(self.oldPosition.lng) != 0 && Number(self.oldPosition.lat) != 0) {
        self.positionPicker.start(new AMap.LngLat(self.oldPosition.lng, self.oldPosition.lat));
      } else {
        if (self.curPos) {
          self.positionPicker.start(new AMap.LngLat(self.curPos[0], self.curPos[1]));
          self.setNewPosition({
            lng: self.curPos[0],
            lat: self.curPos[1]
          });
        }
      }
      self.amap.panBy(0, 1);
    },
    justInitMap() {
      this.$modal.alert("请在设备的设置中开启APP的定位权限后重新获取当前位置");
      this.amap = new AMap.Map("container", {
        showControlButton: true,
        zoom: 18
      });
      let self = this;
      this.$modal.hideLoading();
      AMapUI.loadUI(["misc/PositionPicker"], function(PositionPicker) {
        AMap.PositionPicker = PositionPicker;
        self.loadMarkList();
      });
    },
    // 当前选址位置截图生成方位图url
    async getUrlFromScreenShots() {
      // 当前选址位置截图处理，生成经营场所方位图
      let screenshotUrl = "";
      const canvasBox = document.querySelector("#container") || null;
      const scrollTop = document.documentElement.scrollTop;
      // 左侧计算方法， 元素距离屏幕左侧的距离
      const canvasBoxOffsetLeft = canvasBox ? canvasBox.getBoundingClientRect().left : 0;
      // 顶部计算方法， 元素距离顶部距离 + body滚动高度
      const canvasBoxOffsetTop = canvasBox ? canvasBox.offsetTop + scrollTop : 0;
      try {
        // await接收图片地址
        screenshotUrl = await screenshots({
          canvasBox,
          canvasBoxOffsetLeft,
          canvasBoxOffsetTop
        });
      } catch (err) {
        console.log("err", err);
      }
      return screenshotUrl;
    },
    handleNextStep() {
      const _this = this;
      const { longitude, latitude } = _this.currPosition;
      const curCords = [longitude, latitude];
      // 限制经纬与默认经纬度一致 导致数据问题 fsx 2024-3-8
      if (JSON.stringify(SET_MAP_LAT_LON) === JSON.stringify(curCords)) {
        return _this.$modal.alert("请拖动图标调整位置");
      }
      if (!Object.keys(this.curGridInfo).length) {
        return _this.$modal.alert("请选择网格");
      }
      uni.showModal({
        title: "提示",
        content: "实地核查会用到商户位置截图，请问是否需要截图？",
        success: async function(res) {
          if (!res.confirm) return;
          // 截图并上传
          const screenshotUrl = await _this.getUrlFromScreenShots();
          if (screenshotUrl) {
            await _this.uploadCutFile(screenshotUrl);
            // 路由跳转
            _this.$u.route({
              url: "pages/certificate/fieldAudit/orientationDiagram/mapFieldAudit",
              params: {
                longitude: longitude || "",
                latitude: latitude || ""
              }
            });
          }
        }
      });
    },
    async uploadCutFile(src) {
      // 当前位置信息截图生成经营场所方位图 --上传图片  fsx 2024-2-23 开始
      let uploadParam = {
        bizId: this.$storage.get("curConfirmInfo").curBizUuid,
        fiGroupCode: "l_audit_addr_img",
        fiLogicPath: "l_audit_addr_img"
      };
      // 当前位置信息截图生成经营场所方位图 --上传图片  fsx 2024-2-23 结束
      uploadParam.fileName = Date.now() + ".jpg";
      const _this = this;
      commonService
        .uploadBase64ForApp(src, uploadParam)
        .then(res => {
          if (res.success) {
            // 缓存返回承载信息
            const { longitude, latitude } = _this.currPosition;
            const backCache = {
              addrImg: res.bean,
              position: [longitude, latitude],
              gridInfo: this.curGridInfo
            };
            _this.$storage.set("backCache", backCache);
          } else {
            console.log("上传失败", res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleChooseGrid() {
      this.$u.route({
        url: "pages/certificate/fieldAudit/orientationDiagram/chooseGrid",
        params: {
          curChecked: this.curGridInfo.gridUuid
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

.page {
  padding: 0;
}

#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}

.m-content {
  position: relative;
}

.tips {
  position: absolute;
  width: 100%;
  z-index: 999;
  background-color: #f6f6f6;
  padding: 16rpx 40rpx;
  .bold {
    display: inline-block;
    margin: 0 10rpx;
    font-weight: bold;
  }
}

.m-market {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  padding: 0 30rpx;
}

.row {
  padding: 20rpx 0;
  border-bottom: 1px solid #cecece;
  position: relative;
  color: #666666;
  .row-value {
    color: #333333;
    font-weight: bold;
  }
  .hightlight {
    color: #0070d2;
  }
  .row-button {
    padding: 0 !important;
  }
  .arrow {
    position: absolute;
    right: 0;
    color: #333333;
  }
  /deep/.u-col {
    padding-bottom: 10rpx !important;
  }
}
.u-size-default {
  font-size: 28rpx;
}
</style>
